package com.cn.wanxi.service;

import com.cn.wanxi.IOModel.ProducctIOModel;
import com.cn.wanxi.model.ProducctModel;
import com.cn.wanxi.util.Path;
import com.cn.wanxi.util.ReadAndWriteIO;
import com.cn.wanxi.util.Tool;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ProductService {
    /**
     * 得到网站首页产品展示数据
     *
     * @return
     */
    public List<ProducctModel> getProductListForHome() {

//        1.写入记事本
        writeNote(Path.PRODUCT_PATH.getPath());

//        2.读取记事本
        String results = new ReadAndWriteIO().readNote(Path.PRODUCT_PATH.getPath());

//        3.封装数据

        return setData(results);
    }


    private List<ProducctModel> setData(String result) {
        List<ProducctModel> list = new ArrayList<>();
        String[] results = result.split(Path.SPLIT.getPath());//通过分隔符得到所有数据
        String imghref = results[0];
//        Tool tool=new Tool();
        imghref = Tool.replace(imghref);
        String title = results[1];
        title = Tool.replace(title);
        String content = results[2];
        content = Tool.replace(content);

        String imgHrefs[] = imghref.split(",");
        String titles[] = title.split(",");
        String contents[] = content.split("&&");
        for (int i = 0; i < imgHrefs.length; i++) {
            ProducctModel model = new ProducctModel();
            model.setImgHref(imgHrefs[i]);
            model.setTitle(titles[i]);
            model.setContent(contents[i]);
            list.add(model);
        }
        return list;
    }

    /**
     * 写入记事本
     *
     * @param name  文件名称
     */
    private void writeNote(String name) {
        ProducctIOModel producctIOModel = new ProducctIOModel();
        String[] imghrefs = producctIOModel.getImgHrefs();

        List<String> list = new ArrayList<>();
        list.add(Arrays.toString(imghrefs));
        list.add(Arrays.toString(producctIOModel.getTitles()));
        new ReadAndWriteIO().createNote(name, list);
    }

    private String arrayToString(String[] a) {
        if (a == null)
            return "null";

        int iMax = a.length - 1;
        if (iMax == -1)
            return "[]";

        StringBuilder b = new StringBuilder();
        b.append('[');
        for (int i = 0; ; i++) {
            b.append(String.valueOf(a[i]));
            if (i == iMax)
                return b.append(']').toString();
            b.append("&&");
        }
    }
}
